package com.dchh.android.suverynew.act;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.location.Location;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.view.MyLoadingDialog;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.StringUtil;
import com.dhcc.android.base.utils.amap.AMapUtil;
import com.dhcc.android.base.utils.amap.TTSController;

import java.util.ArrayList;
import java.util.List;

/**
 * 初始化界面，用于设置起点终点，发起路径计算导航等
 * 
 */
@SuppressLint("ResourceAsColor")
public class NaviMainActivity extends SBaseActivity implements
OnClickListener, OnCheckedChangeListener, LocationSource,
AMapLocationListener, AMapNaviListener {
	// --------------View基本控件---------------------
	private MapView mMapView;// 地图控件
	private RadioGroup mNaviMethodGroup;// 步行驾车选择控件
	public Dialog dialog, dialog2;
	private AutoCompleteTextView mStrategyText;// 行车策略输入
	private LinearLayout mRouteButton;

	// 地图和导航核心逻辑类
	private AMap mAmap;
	private AMapNavi mAmapNavi;

	// ---------------------变量---------------------
	private String[] mStrategyMethods;// 记录行车策略的数组
	// 驾车路径规划起点，途经点，终点的list
	private List<NaviLatLng> mStartPoints = new ArrayList<NaviLatLng>();
	private List<NaviLatLng> mEndPoints = new ArrayList<NaviLatLng>();
	// 记录起点、终点、途经点位置
	private NaviLatLng mStartPoint = new NaviLatLng();
	private NaviLatLng mEndPoint = new NaviLatLng();
	// 记录起点、终点、途经点在地图上添加的Marker

	// 记录导航种类，用于记录当前选择是驾车还是步行
	private int mTravelMethod = DRIVER_NAVI_METHOD;
	private static final int DRIVER_NAVI_METHOD = 0;// 驾车导航
	private static final int WALK_NAVI_METHOD = 1;// 步行导航

	// 计算路的状态
	private final static int GPSNO = 0;// 使用我的位置进行计算、GPS定位还未成功状态
	private final static int CALCULATEERROR = 1;// 启动路径计算失败状态
	private final static int CALCULATESUCCESS = 2;// 启动路径计算成功状态
	private OnLocationChangedListener mListener;
	private LocationManagerProxy mAMapLocationManager;
	private Double endLon, endLat;
	public Bundle savedInstanceState;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.savedInstanceState = savedInstanceState;
		setContentView(R.layout.task_navi);
	}

	// -----------------初始化-------------------

	/**
	 * 初始化界面所需View控件
	 * 
	 */

	@Override
	public void initView() {
		TTSController.getInstance(this).startSpeaking();
		endLon = Constants.TargetXY[1];
		endLat = Constants.TargetXY[0];
		dialog = MyLoadingDialog.createLoadingDialog(this, "线路规划中...");
		dialog2 = MyLoadingDialog.createLoadingDialog(this, "定位中...");
		dialog2.show();
		MapsInitializer.sdcardDir = AMapUtil.getSdCacheDir(this);
		mMapView = (MapView) findViewById(R.id.map);
		mMapView.onCreate(savedInstanceState);
		mAmap = mMapView.getMap();
		setUpMap();
		mStrategyText = (AutoCompleteTextView) findViewById(R.id.navi_strategy_edit);
		mStrategyText.setDropDownBackgroundResource(R.drawable.whitedownborder);
		mStrategyText.setInputType(InputType.TYPE_NULL);
		initResources();
		ArrayAdapter<String> strategyAdapter = new ArrayAdapter<String>(this,
				R.layout.task_navi_strategy_inputs, mStrategyMethods);
		mStrategyText.setAdapter(strategyAdapter);

		mRouteButton = (LinearLayout) findViewById(R.id.navi_route_button);// 在线导航
		initNaviBtn();
		mNaviMethodGroup = (RadioGroup) findViewById(R.id.navi_method_radiogroup);
		initListener();
		initMapAndNavi();
		mEndPoints.clear();
		mEndPoint = new NaviLatLng(endLon, endLat);// ？？填写终点位置
		mEndPoints.add(mEndPoint);
		setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				goBack();
			}
		});
	}
	//------------------------初始化导航按钮----------------------------------
	/**
	 * 初始化导航按钮
	 */
	private void initNaviBtn(){
		TextView navi_route_text=(TextView) findViewById(R.id.navi_route_text);
		mRouteButton.setOnClickListener(this);
		mRouteButton.setClickable(true);
		mRouteButton.setBackgroundResource(R.drawable.ll_bg_d6_blue);
		navi_route_text.setTextColor(this.getResources().getColor(
				R.color.font_blue));
	}

	/**
	 * 设置一些amap的属性
	 */
	private void setUpMap() {
		mAmap.setLocationSource(this);// 设置定位监听
		mAmap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		mAmap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		// 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
		mAmap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
	}

	/**
	 * 初始化资源文件，主要是字符串
	 */
	private void initResources() {
		mStrategyMethods = new String[] { "速度最快", "避免收费", "距离最短", "不走高速快速路",
				"时间最短且躲避拥堵", "避免收费且躲避拥堵" };
	}

	/**
	 * 初始化所需监听
	 */
	private void initListener() {
		mStrategyText.setOnClickListener(this);
		mNaviMethodGroup.setOnCheckedChangeListener(this);
	}

	/**
	 * 初始化地图和导航相关内容
	 */
	private void initMapAndNavi() {
		// 初始语音播报资源
		setVolumeControlStream(AudioManager.STREAM_MUSIC);// 设置声音控制
		// 语音播报开始

		mAmapNavi = AMapNavi.getInstance(this);// 初始化导航引擎

		mAmapNavi.startGPS();
	}

	// ----------具体处理方法--------------
	/**
	 * 算路的方法，根据选择可以进行行车和步行两种方式进行路径规划
	 */
	private void calculateRoute() {
		// 显示路径规划的窗体
		dialog.show();
		switch (mTravelMethod) {
		// 驾车导航
		case DRIVER_NAVI_METHOD:
			int driverIndex = calculateDriverRoute();
			if (driverIndex == CALCULATEERROR) {
				CommenUtil.toast("路线计算失败,检查参数情况", NaviMainActivity.this);
				return;
			} else if (driverIndex == GPSNO) {
				return;
			}
			break;
			// 步行导航
		case WALK_NAVI_METHOD:
			int walkIndex = calculateWalkRoute();
			if (walkIndex == CALCULATEERROR) {
				CommenUtil.toast("路线计算失败,检查参数情况", NaviMainActivity.this);
				return;
			} else if (walkIndex == GPSNO) {
				return;
			}
			break;
		}

	}

	/**
	 * 对行车路线进行规划
	 */
	private int calculateDriverRoute() {
		int driveMode = getDriveMode();
		int code = CALCULATEERROR;

		if (mAmapNavi.calculateDriveRoute(mStartPoints, mEndPoints, null,
				driveMode)) {
			code = CALCULATESUCCESS;
		} else {

			code = CALCULATEERROR;
		}

		return code;
	}

	/**
	 * 对步行路线进行规划
	 */
	private int calculateWalkRoute() {
		int code = CALCULATEERROR;
		if (mAmapNavi.calculateWalkRoute(mStartPoint, mEndPoint)) {
			code = CALCULATESUCCESS;
		} else {
			code = CALCULATEERROR;
		}
		return code;
	}
	/**
	 * 无网情况下，直线导航实现方法
	 */
	private void lineNavi() {
		// add 杨宗仁
//		Intent intent = new Intent(NaviMainActivity.this,
//				NaviLineActivity.class);
//		intent.putExtra("endLon", endLon);
//		intent.putExtra("endLat", endLat);
//		startActivity(intent);
	}
	/**
	 * 根据选择，获取行车策略
	 */
	private int getDriveMode() {
		String strategyMethod = mStrategyText.getText().toString();
		// 速度优先
		if (mStrategyMethods[0].equals(strategyMethod)) {
			return AMapNavi.DrivingDefault;
		}
		// 花费最少
		else if (mStrategyMethods[1].equals(strategyMethod)) {
			return AMapNavi.DrivingSaveMoney;

		}
		// 距离最短
		else if (mStrategyMethods[2].equals(strategyMethod)) {
			return AMapNavi.DrivingShortDistance;
		}
		// 不走高速
		else if (mStrategyMethods[3].equals(strategyMethod)) {
			return AMapNavi.DrivingNoExpressways;
		}
		// 时间最短且躲避拥堵
		else if (mStrategyMethods[4].equals(strategyMethod)) {
			return AMapNavi.DrivingFastestTime;
		} else if (mStrategyMethods[5].equals(strategyMethod)) {
			return AMapNavi.DrivingAvoidCongestion;
		} else {
			return AMapNavi.DrivingDefault;
		}
	}

	// -------------定位----------------
	@Override
	public void onLocationChanged(Location location) {
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onProviderDisabled(String provider) {
	}

	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		boolean isSuccess=false;
		StringUtil.dismissDialog(dialog2);
		String location = CommenUtil.getLatLon();// GPS获取当前地址经纬度
		String lat = "", lon = "";
		if (StringUtil.isNotEmpty(location)) {
			lat = location.split(",")[0];
			lon = location.split(",")[1];
		}
		if(!lat.contains("0.0")||!lon.contains("0.0")){//定义不对
			isSuccess=true;
		}else{
			if (mListener != null && amapLocation != null) {
				if (amapLocation != null
						&& amapLocation.getAMapException().getErrorCode() == 0) {
					isSuccess=true;
					mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
					lat=amapLocation.getLatitude()+"";
					lon=amapLocation.getLongitude()+"";
				} 
			}
		}
		if(isSuccess){
			System.out.println("start:"+Double.parseDouble(lat)+","+Double.parseDouble(lon));
			mStartPoint = new NaviLatLng(Double.parseDouble(lat),Double.parseDouble(lon));
			mStartPoints.clear();
			mStartPoints.add(mStartPoint);
		}else{
			CommenUtil.toast("定位出现异常,请检查网络或GPS的打开情况", NaviMainActivity.this);
		}
	}

	@Override
	public void activate(OnLocationChangedListener listener) {

		mListener = listener;
		if (mAMapLocationManager == null) {
			mAMapLocationManager = LocationManagerProxy.getInstance(this);
			// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
			// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
			// 在定位结束后，在合适的生命周期调用destroy()方法
			// 其中如果间隔时间为-1，则定位只定一次
			// 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除

			// 取得网络配置历史记录
			String gpsRefreahTime = SPreferencesManager.getValue(
					MSApplication.GPS_REFRESH_TIME, "5");
			String catchRange = SPreferencesManager.getValue(MSApplication.CATCH_RANGE, "10");// 定位时间、精度？？？
			mAMapLocationManager.requestLocationData(
					LocationProviderProxy.AMapNetwork,
					Integer.parseInt(gpsRefreahTime) * 1000,
					Integer.parseInt(catchRange), this);
		}
	}

	@Override
	public void deactivate() {
		mListener = null;
		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destroy();
		}
		mAMapLocationManager = null;

	}

	// ----------------------事件处理---------------------------

	/**
	 * 控件点击事件监听
	 * */
	@Override
	public void onClick(View v) {
		if(v.getId()==R.id.navi_route_button){
			// 路径规划按钮处理事件
			if (StringUtil.isFastDoubleClick(500)) {
				return;
			}
			calculateRoute();
		}else if(v.getId()== R.id.navi_strategy_edit){
			if (StringUtil.isFastDoubleClick(500)) {
				return;
			}
			mStrategyText.showDropDown();
		}
	}

	/**
	 * 驾车、步行选择按钮事件监听
	 * */
	@SuppressLint("ResourceAsColor")
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {

		if (checkedId==R.id.navi_driver_button){
		// 驾车模式
			mTravelMethod = DRIVER_NAVI_METHOD;
			// 驾车可以途经点和策略的设置
			mStrategyText.setEnabled(true);
		}else if(checkedId==R.id.navi_walk_button){
			// 步行导航模式
			mTravelMethod = WALK_NAVI_METHOD;
			mStrategyText.setEnabled(false);
		}
	}

	// -------------生命周期必须重写方法----------------
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);
	}

	@Override
	public void onResume() {
		super.onResume();
		mMapView.onResume();
		// 以上两句必须重写
		// 以下两句逻辑是为了保证进入首页开启定位和加入导航回调
		mAmapNavi.setAMapNaviListener(this);
		mAmapNavi.startGPS();
		TTSController.getInstance(this).startSpeaking();
	}

	@Override
	public void onPause() {
		super.onPause();
		mMapView.onPause();
		// 以上两句必须重写
		// 下边逻辑是移除监听
		mAmapNavi.removeAMapNaviListener(this);
		deactivate();
		System.out.println("onDestroy");
	}

	@Override
	protected void setTitle(TextView toolbar_title) {
		toolbar_title.setText("策略选择");
	}

	@Override
	public void onDestroy() {
		new MSApplication().deleteActivity(this);
		mMapView.onDestroy();
		mAmapNavi.removeAMapNaviListener(this);
		System.out.println("onDestroy");
		super.onDestroy();
	}

	public void goBack() {
		if (StringUtil.isFastDoubleClick(500)) {
			return;
		}
		Constants.radioPageViewFlag = 0;
		finish();
	}

	/**
	 * 返回键处理事件
	 * */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goBack();
		}
		return super.onKeyDown(keyCode, event);
	}

	OnClickListener backListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			goBack();
		}
	};

	@Override
	public void onTrafficStatusUpdate() {

	}

	@Override
	public void onStartNavi(int arg0) {

	}

	@Override
	public void onReCalculateRouteForYaw() {

	}

	@Override
	public void onReCalculateRouteForTrafficJam() {

	}

	@Override
	public void onLocationChange(AMapNaviLocation location) {

	}

	@Override
	public void onInitNaviSuccess() {

	}

	@Override
	public void onInitNaviFailure() {

	}

	@Override
	public void onGetNavigationText(int arg0, String arg1) {
		System.out.println("求声音啊:" + arg1);
	}

	@Override
	public void onEndEmulatorNavi() {

	}

	@Override
	public void onCalculateRouteSuccess() {
		StringUtil.dismissDialog(dialog);
		Intent intent = new Intent(NaviMainActivity.this,
				NaviCustomActivity.class);
		startActivity(intent);
	}

	@Override
	public void onCalculateRouteFailure(int arg0) {
		StringUtil.dismissDialog(dialog);
		CommenUtil.toast("路径规划出错", NaviMainActivity.this);
	}

	@Override
	public void onArrivedWayPoint(int arg0) {

	}

	@Override
	public void onArriveDestination() {

	}

	@Override
	public void onGpsOpenStatus(boolean arg0) {

	}

	@Override
	public void onNaviInfoUpdated(AMapNaviInfo arg0) {

	}

	@Override
	public void onNaviInfoUpdate(NaviInfo arg0) {

	}

}